// 成就系统
class AchievementsSystem {
    constructor() {
        this.achievements = this.initializeAchievements();
        this.unlockedAchievements = this.loadUnlockedAchievements();
        this.stats = this.loadStats();
    }
    
    // 初始化成就定义
    initializeAchievements() {
        return {
            // 故事创作成就
            first_story: {
                id: 'first_story',
                title: '初出茅庐',
                description: '完成第一个故事',
                icon: '📝',
                category: 'story',
                condition: { type: 'story_count', value: 1 }
            },
            story_5: {
                id: 'story_5',
                title: '小小作家',
                description: '完成5个故事',
                icon: '✏️',
                category: 'story',
                condition: { type: 'story_count', value: 5 }
            },
            story_10: {
                id: 'story_10',
                title: '故事达人',
                description: '完成10个故事',
                icon: '📚',
                category: 'story',
                condition: { type: 'story_count', value: 10 }
            },
            words_500: {
                id: 'words_500',
                title: '文思泉涌',
                description: '累计创作500字',
                icon: '💭',
                category: 'story',
                condition: { type: 'total_words', value: 500 }
            },
            words_2000: {
                id: 'words_2000',
                title: '文笔流畅',
                description: '累计创作2000字',
                icon: '🖋️',
                category: 'story',
                condition: { type: 'total_words', value: 2000 }
            },
            long_story: {
                id: 'long_story',
                title: '长篇大论',
                description: '单个故事超过300字',
                icon: '📄',
                category: 'story',
                condition: { type: 'single_story_words', value: 300 }
            },
            
            // 成语学习成就
            first_idiom: {
                id: 'first_idiom',
                title: '成语新手',
                description: '学会第一个成语',
                icon: '🎯',
                category: 'idiom',
                condition: { type: 'idiom_count', value: 1 }
            },
            idiom_10: {
                id: 'idiom_10',
                title: '成语初学者',
                description: '学会10个成语',
                icon: '📖',
                category: 'idiom',
                condition: { type: 'idiom_count', value: 10 }
            },
            idiom_25: {
                id: 'idiom_25',
                title: '成语达人',
                description: '学会25个成语',
                icon: '🏮',
                category: 'idiom',
                condition: { type: 'idiom_count', value: 25 }
            },
            chain_5: {
                id: 'chain_5',
                title: '接龙高手',
                description: '完成5轮成语接龙',
                icon: '🔄',
                category: 'idiom',
                condition: { type: 'chain_length', value: 5 }
            },
            chain_10: {
                id: 'chain_10',
                title: '接龙大师',
                description: '完成10轮成语接龙',
                icon: '🎮',
                category: 'idiom',
                condition: { type: 'chain_length', value: 10 }
            },
            
            // 里程碑成就
            first_day: {
                id: 'first_day',
                title: '初次体验',
                description: '第一天使用应用',
                icon: '🌅',
                category: 'milestone',
                condition: { type: 'study_days', value: 1 }
            },
            week_7: {
                id: 'week_7',
                title: '坚持一周',
                description: '连续学习7天',
                icon: '📅',
                category: 'milestone',
                condition: { type: 'streak_days', value: 7 }
            },
            month_30: {
                id: 'month_30',
                title: '月度学习者',
                description: '连续学习30天',
                icon: '🌙',
                category: 'milestone',
                condition: { type: 'streak_days', value: 30 }
            },
            xp_100: {
                id: 'xp_100',
                title: '经验丰富',
                description: '累计获得100经验值',
                icon: '⭐',
                category: 'milestone',
                condition: { type: 'total_xp', value: 100 }
            },
            xp_500: {
                id: 'xp_500',
                title: '学习大师',
                description: '累计获得500经验值',
                icon: '🌟',
                category: 'milestone',
                condition: { type: 'total_xp', value: 500 }
            },
            all_story_achievements: {
                id: 'all_story_achievements',
                title: '故事专家',
                description: '解锁所有故事相关成就',
                icon: '👑',
                category: 'milestone',
                condition: { type: 'category_complete', value: 'story' }
            },
            all_idiom_achievements: {
                id: 'all_idiom_achievements',
                title: '成语专家',
                description: '解锁所有成语相关成就',
                icon: '🏆',
                category: 'milestone',
                condition: { type: 'category_complete', value: 'idiom' }
            }
        };
    }
    
    // 检查成就条件
    checkAchievement(achievementId, currentValue) {
        const achievement = this.achievements[achievementId];
        if (!achievement) return false;
        
        const condition = achievement.condition;
        switch (condition.type) {
            case 'story_count':
            case 'total_words':
            case 'single_story_words':
            case 'idiom_count':
            case 'chain_length':
            case 'study_days':
            case 'streak_days':
            case 'total_xp':
                return currentValue >= condition.value;
            case 'category_complete':
                return this.isCategoryComplete(condition.value);
            default:
                return false;
        }
    }
    
    // 检查所有成就
    checkAllAchievements(currentStats) {
        const newUnlocks = [];
        
        Object.keys(this.achievements).forEach(achievementId => {
            if (!this.unlockedAchievements.includes(achievementId)) {
                const achievement = this.achievements[achievementId];
                const condition = achievement.condition;
                
                let shouldUnlock = false;
                switch (condition.type) {
                    case 'story_count':
                        shouldUnlock = currentStats.storyCount >= condition.value;
                        break;
                    case 'total_words':
                        shouldUnlock = currentStats.totalWords >= condition.value;
                        break;
                    case 'single_story_words':
                        shouldUnlock = currentStats.maxStoryWords >= condition.value;
                        break;
                    case 'idiom_count':
                        shouldUnlock = currentStats.idiomCount >= condition.value;
                        break;
                    case 'chain_length':
                        shouldUnlock = currentStats.maxChainLength >= condition.value;
                        break;
                    case 'study_days':
                        shouldUnlock = currentStats.studyDays >= condition.value;
                        break;
                    case 'streak_days':
                        shouldUnlock = currentStats.currentStreak >= condition.value;
                        break;
                    case 'total_xp':
                        shouldUnlock = currentStats.totalXP >= condition.value;
                        break;
                    case 'category_complete':
                        shouldUnlock = this.isCategoryComplete(condition.value);
                        break;
                }
                
                if (shouldUnlock) {
                    this.unlockAchievement(achievementId);
                    newUnlocks.push(achievement);
                }
            }
        });
        
        return newUnlocks;
    }
    
    // 解锁成就
    unlockAchievement(achievementId) {
        if (!this.unlockedAchievements.includes(achievementId)) {
            this.unlockedAchievements.push(achievementId);
            this.saveUnlockedAchievements();
            this.showAchievementNotification(this.achievements[achievementId]);
        }
    }
    
    // 显示成就解锁通知
    showAchievementNotification(achievement) {
        const notification = document.createElement('div');
        notification.className = 'achievement-notification achievement-unlock';
        notification.innerHTML = `
            <h4>🎉 成就解锁！</h4>
            <p><strong>${achievement.icon} ${achievement.title}</strong></p>
            <p>${achievement.description}</p>
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.style.animation = 'slideOutRight 0.5s ease';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 500);
        }, 3000);
    }
    
    // 检查分类是否完成
    isCategoryComplete(category) {
        return Object.values(this.achievements)
            .filter(achievement => achievement.category === category)
            .every(achievement => this.unlockedAchievements.includes(achievement.id));
    }
    
    // 获取成就进度
    getAchievementProgress(achievementId, currentValue) {
        const achievement = this.achievements[achievementId];
        if (!achievement) return { current: 0, target: 0, percentage: 0 };
        
        const target = achievement.condition.value;
        const percentage = Math.min(100, Math.round((currentValue / target) * 100));
        
        return { current: currentValue, target, percentage };
    }
    
    // 计算经验值
    calculateXP(action, value) {
        const xpRates = {
            story_word: 1,      // 每字1XP
            idiom_learned: 5,   // 每个成语5XP
            chain_turn: 3,      // 每轮接龙3XP
            daily_login: 10,    // 每日登录10XP
            story_complete: 20 // 完成故事20XP
        };
        
        return (xpRates[action] || 0) * value;
    }
    
    // 加载已解锁成就
    loadUnlockedAchievements() {
        const saved = localStorage.getItem('achievements_unlocked');
        return saved ? JSON.parse(saved) : [];
    }
    
    // 保存已解锁成就
    saveUnlockedAchievements() {
        localStorage.setItem('achievements_unlocked', JSON.stringify(this.unlockedAchievements));
    }
    
    // 加载统计数据
    loadStats() {
        const saved = localStorage.getItem('learning_stats');
        if (saved) {
            return JSON.parse(saved);
        }
        
        return {
            storyCount: 0,
            totalWords: 0,
            maxStoryWords: 0,
            idiomCount: 0,
            maxChainLength: 0,
            studyDays: 0,
            currentStreak: 0,
            lastStudyDate: null,
            totalXP: 0,
            todayXP: 0,
            dailyStats: {}
        };
    }
    
    // 保存统计数据
    saveStats() {
        localStorage.setItem('learning_stats', JSON.stringify(this.stats));
    }
    
    // 更新统计数据
    updateStats(action, value) {
        const today = new Date().toDateString();
        
        // 更新今日统计
        if (!this.stats.dailyStats[today]) {
            this.stats.dailyStats[today] = {
                words: 0,
                idioms: 0,
                turns: 0,
                stories: 0,
                xp: 0
            };
            
            // 更新学习天数和连击
            this.updateStudyStreak();
        }
        
        // 根据动作更新统计
        switch (action) {
            case 'story_word':
                this.stats.totalWords += value;
                this.stats.maxStoryWords = Math.max(this.stats.maxStoryWords, value);
                this.stats.dailyStats[today].words += value;
                break;
            case 'idiom_learned':
                this.stats.idiomCount += value;
                this.stats.dailyStats[today].idioms += value;
                break;
            case 'chain_turn':
                this.stats.dailyStats[today].turns += value;
                break;
            case 'story_complete':
                this.stats.storyCount += value;
                this.stats.dailyStats[today].stories += value;
                break;
        }
        
        // 计算并添加经验值
        const xpGained = this.calculateXP(action, value);
        this.stats.totalXP += xpGained;
        this.stats.todayXP += xpGained;
        this.stats.dailyStats[today].xp += xpGained;
        
        this.saveStats();
        
        // 检查成就
        return this.checkAllAchievements(this.stats);
    }
    
    // 更新学习连击
    updateStudyStreak() {
        const today = new Date().toDateString();
        const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toDateString();
        
        if (this.stats.lastStudyDate === today) {
            // 今天已经学习过了
            return;
        } else if (this.stats.lastStudyDate === yesterday) {
            // 连续学习
            this.stats.currentStreak += 1;
        } else {
            // 中断了连击
            this.stats.currentStreak = 1;
        }
        
        this.stats.lastStudyDate = today;
        this.stats.studyDays += 1;
    }
    
    // 获取统计数据
    getStats() {
        return { ...this.stats };
    }
    
    // 获取成就数据
    getAchievements() {
        return this.achievements;
    }
    
    // 获取已解锁成就
    getUnlockedAchievements() {
        return this.unlockedAchievements;
    }
}

// 统计界面管理器
class StatsManager {
    constructor(achievementsSystem) {
        this.achievements = achievementsSystem;
        this.initializeElements();
        this.bindEvents();
    }
    
    // 初始化元素
    initializeElements() {
        this.statsBtn = document.getElementById('statsBtn');
        this.statsModal = document.getElementById('statsModal');
        this.statsTabs = document.querySelectorAll('.stats-tab');
        this.statsPanels = document.querySelectorAll('.stats-panel');
        
        // 统计元素
        this.totalStoryWords = document.getElementById('totalStoryWords');
        this.totalStoryTurns = document.getElementById('totalStoryTurns');
        this.totalStories = document.getElementById('totalStories');
        this.totalStoryTime = document.getElementById('totalStoryTime');
        this.todayStoryWords = document.getElementById('todayStoryWords');
        this.todayStoryProgress = document.getElementById('todayStoryProgress');
        
        this.totalIdiomsLearned = document.getElementById('totalIdiomsLearned');
        this.totalIdiomTurns = document.getElementById('totalIdiomTurns');
        this.totalIdiomTime = document.getElementById('totalIdiomTime');
        this.idiomChainLength = document.getElementById('idiomChainLength');
        this.idiomMasteryCount = document.getElementById('idiomMasteryCount');
        this.idiomMasteryProgress = document.getElementById('idiomMasteryProgress');
        
        this.totalXP = document.getElementById('totalXP');
        this.totalAchievements = document.getElementById('totalAchievements');
        this.studyDays = document.getElementById('studyDays');
        this.currentStreak = document.getElementById('currentStreak');
        this.streakCalendar = document.getElementById('streakCalendar');
        
        this.resetStatsBtn = document.getElementById('resetStatsBtn');
    }
    
    // 绑定事件
    bindEvents() {
        if (this.statsBtn) {
            this.statsBtn.addEventListener('click', () => this.showStatsModal());
        }
        
        this.statsTabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const targetStats = tab.dataset.stats;
                this.switchStatsTab(targetStats);
            });
        });
        
        // 关闭按钮
        document.querySelectorAll('.stats-modal-close').forEach(btn => {
            btn.addEventListener('click', () => this.hideStatsModal());
        });
        
        if (this.resetStatsBtn) {
            this.resetStatsBtn.addEventListener('click', () => this.resetStats());
        }
        
        // 点击背景关闭
        if (this.statsModal) {
            this.statsModal.addEventListener('click', (e) => {
                if (e.target === this.statsModal) {
                    this.hideStatsModal();
                }
            });
        }
    }
    
    // 显示统计模态框
    showStatsModal() {
        this.updateStatsDisplay();
        this.statsModal.classList.add('show');
    }
    
    // 隐藏统计模态框
    hideStatsModal() {
        this.statsModal.classList.remove('show');
    }
    
    // 切换统计标签
    switchStatsTab(targetStats) {
        this.statsTabs.forEach(tab => {
            tab.classList.remove('active');
            if (tab.dataset.stats === targetStats) {
                tab.classList.add('active');
            }
        });
        
        this.statsPanels.forEach(panel => {
            panel.classList.remove('active');
            if (panel.id === `${targetStats}StatsPanel`) {
                panel.classList.add('active');
            }
        });
    }
    
    // 更新统计显示
    updateStatsDisplay() {
        const stats = this.achievements.getStats();
        
        // 故事统计
        if (this.totalStoryWords) this.totalStoryWords.textContent = stats.totalWords.toLocaleString();
        if (this.totalStoryTurns) this.totalStoryTurns.textContent = stats.totalWords; // 简化显示
        if (this.totalStories) this.totalStories.textContent = stats.storyCount;
        if (this.totalStoryTime) this.totalStoryTime.textContent = this.formatTime(stats.totalWords * 2); // 估算时间
        
        // 今日进度
        const today = new Date().toDateString();
        const todayStats = stats.dailyStats[today] || { words: 0 };
        if (this.todayStoryWords) this.todayStoryWords.textContent = todayStats.words.toLocaleString();
        if (this.todayStoryProgress) {
            const progress = Math.min(100, (todayStats.words / 100) * 100); // 目标100字
            this.todayStoryProgress.style.width = `${progress}%`;
        }
        
        // 成语统计
        if (this.totalIdiomsLearned) this.totalIdiomsLearned.textContent = stats.idiomCount;
        if (this.totalIdiomTurns) this.totalIdiomTurns.textContent = stats.idiomCount; // 简化显示
        if (this.totalIdiomTime) this.totalIdiomTime.textContent = this.formatTime(stats.idiomCount * 3); // 估算时间
        if (this.idiomChainLength) this.idiomChainLength.textContent = stats.maxChainLength;
        
        // 成语掌握度
        const masteryCount = Math.min(25, stats.idiomCount); // 目标25个成语
        if (this.idiomMasteryCount) this.idiomMasteryCount.textContent = masteryCount;
        if (this.idiomMasteryProgress) {
            const masteryProgress = (masteryCount / 25) * 100;
            this.idiomMasteryProgress.style.width = `${masteryProgress}%`;
        }
        
        // 总体统计
        if (this.totalXP) this.totalXP.textContent = stats.totalXP.toLocaleString();
        if (this.totalAchievements) this.totalAchievements.textContent = this.achievements.unlockedAchievements.length;
        if (this.studyDays) this.studyDays.textContent = stats.studyDays;
        if (this.currentStreak) this.currentStreak.textContent = stats.currentStreak;
        
        // 生成学习日历
        if (this.streakCalendar) {
            this.generateStreakCalendar();
        }
    }
    
    // 格式化时间
    formatTime(minutes) {
        if (minutes < 60) {
            return `${Math.round(minutes)}分钟`;
        } else {
            const hours = Math.floor(minutes / 60);
            const remainingMinutes = Math.round(minutes % 60);
            return `${hours}小时${remainingMinutes}分钟`;
        }
    }
    
    // 生成学习日历
    generateStreakCalendar() {
        const calendar = this.streakCalendar;
        const stats = this.achievements.getStats();
        const today = new Date();
        
        let html = '';
        
        // 生成最近30天的日历
        for (let i = 29; i >= 0; i--) {
            const date = new Date(today);
            date.setDate(date.getDate() - i);
            const dateString = date.toDateString();
            
            const hasStudied = stats.dailyStats[dateString] && stats.dailyStats[dateString].words > 0;
            const isToday = dateString === today.toDateString();
            
            let dayClass = 'streak-day';
            if (hasStudied) dayClass += ' active';
            if (isToday) dayClass += ' today';
            
            html += `<div class="${dayClass}" title="${date.toLocaleDateString()}">${date.getDate()}</div>`;
        }
        
        calendar.innerHTML = html;
    }
    
    // 重置统计
    resetStats() {
        if (confirm('确定要重置所有统计数据吗？这将清除所有学习记录和成就！')) {
            localStorage.removeItem('learning_stats');
            localStorage.removeItem('achievements_unlocked');
            
            // 重置成就系统
            this.achievements.unlockedAchievements = [];
            this.achievements.stats = this.achievements.loadStats();
            
            // 更新显示
            this.updateStatsDisplay();
            
            // 显示成功消息
            if (window.storyChain) {
                window.storyChain.showMessage('重置成功', '所有统计数据已重置，重新开始你的学习之旅吧！');
            }
            
            this.hideStatsModal();
        }
    }
}

// 导出类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { AchievementsSystem, StatsManager };
}